//资源管理类
window._GRM = {

    sence:null,
    loadPrefabIndex:0,
    nodecreate:{},//记录实例化对象数量
    node:{},//存储实例化对象的对象池集合
    prefab:{},//存储加载好的预制资源
    prefabIndex:[
        {name:'player',path:'prefab/player'},//移动单位节点
        {name:'npcSign',path:'prefab/npcSign'},//移动单位节点
        {name:'fighter',path:'prefab/fightNode'},//战斗单位节点
        {name:'armyFactory',path:'prefab/armyFactory'},//兵营
        {name:'hit',path:'prefab/hit'},//特效动画
        //{name:'statusSign',path:'prefab/statusSign'},//状态
        {name:'choiceUi',path:'prefab/ui/choiceUi'},//选择框
        {name:'tips',path:'prefab/ui/tips'},//提示框
        {name:'jobDetails',path:'prefab/ui/jobDetails'},//转职框
        {name:'upgrade',path:'prefab/ui/upgrade'},//锻造框
        {name:'bossLabel',path:'prefab/ui/bossLabel'},//传家宝
        {name:'DIYequipDetails',path:'prefab/ui/DIYequipDetails'},//传家宝
        {name:'attrSelectLabel',path:'prefab/ui/attrSelectLabel'},//属性选择
        {name:'skillSelectLabel',path:'prefab/ui/skillSelectLabel'},//技能选择框
        {name:'roleLabel',path:'prefab/ui/roleLabel'},
        {name:'talk',path:'prefab/ui/talk'},//对话框
        {name:'roleInfoLabel',path:'prefab/ui/roleInfoLabel'},//角色详情
        {name:'npcInfoLabel',path:'prefab/ui/npcInfoLabel'},//图鉴角色详情
        {name:'goodsLabel',path:'prefab/ui/goodsLabel'},//仓库
        {name:'equipDetails',path:'prefab/ui/equipDetails'},//道具详情
        {name:'jiuguan1',path:'prefab/ui/jiuguan1'},//酒馆
        {name:'nmbLabel',path:'prefab/ui/nmbLabel'},//数值界面
        //{name:'fightCitySelect',path:'prefab/ui/fightCitySelect'},//攻城界面
        //{name:'cenjiuLabel',path:'prefab/ui/cenjiuLabel'},//成就界面
        //{name:'status',path:'prefab/ui/status'},//成就界面
        {name:'mapSelect',path:'prefab/ui/siliLabel'},//小地图
        //{name:'globalxw',path:'prefab/ui/xiuwei'},//全局修为界面
        {name:'explainLabel',path:'prefab/ui/explainLabel'},//说明
        {name:'explaindetail',path:'prefab/ui/explaindetail'},//说明详情

        {name:'duihuangLabel',path:'prefab/ui/duihuangLabel'},//积分ui
        {name:'tujian',path:'prefab/ui/tujian'},//积分ui

        //{name:'inlay',path:'prefab/ui/inlay'},//镶嵌
        {name:'shop',path:'prefab/ui/shop'},//商店
        {name:'woodShop',path:'prefab/ui/woodShop'},//商店
        //{name:'forging',path:'prefab/ui/forging'},//打造

        {name:'troops',path:'prefab/ui/troops'},//人脉
        {name:'cenjiu',path:'prefab/ui/cenjiu'},//成就
        {name:'cenjiuTz',path:'prefab/ui/cenjiuTz'},//挑战成就
        {name:'saveTeam',path:'prefab/ui/saveTeam'},//寄存
        {name:'renwuLabel',path:'prefab/ui/renwuLabel'},//任务
        {name:'ronghe',path:'prefab/ui/ronhe'},//融合
        {name:'tzui',path:'prefab/ui/tiaozan'},//挑战
        {name:'xiangqian',path:'prefab/ui/xiangqiang'},//符文
        {name:'jiuguanshop',path:'prefab/ui/jiuguanshop'},//酒馆商店
        {name:'taskTips',path:'prefab/ui/taskTips'},//酒馆商店
        {name:'selectHelp',path:'prefab/ui/selectHelp'},//善恶说明
        {name:'rhtj',path:'prefab/ui/rhtj'},//融合推荐

        //头像
        //{name:'touxiang',path:'plist/touxiang-0',type:'SpriteAtlas'},
        {name:'touxiang2',path:'plist/touxian_xiyou',type:'SpriteAtlas'},

        //技能动画
        {name:'jineng',path:'plist/jineng',type:'SpriteAtlas'},
        {name:'jineng1',path:'plist/jineng_0',type:'SpriteAtlas'},
        //{name:'jineng2',path:'plist/jineng_1',type:'SpriteAtlas'},
        //{name:'jineng3',path:'plist/jineng_2',type:'SpriteAtlas'},

        //状态
        //{name:'buff',path:'plist/buff',type:'SpriteAtlas'},

        //装备道具
        {name:'equip',path:'plist/zuanbei',type:'SpriteAtlas'},

        //人物动画
        {name:'gonji1',path:'plist/xiyou_npc_gj_1',type:'SpriteAtlas'},
        {name:'xinzou1',path:'plist/xiyou_npc_xz_1',type:'SpriteAtlas'},

        {name:'gonji2',path:'plist/xiyou_npc_gj_2',type:'SpriteAtlas'},
        {name:'xinzou2',path:'plist/xiyou_npc_xz_2',type:'SpriteAtlas'},

        {name:'gonji3',path:'plist/xiyou_npc_gj_3',type:'SpriteAtlas'},
        {name:'xinzou3',path:'plist/xiyou_npc_xz_3',type:'SpriteAtlas'},

        {name:'gonji4',path:'plist/xiyou_npc_gj_4',type:'SpriteAtlas'},
        {name:'xinzou4',path:'plist/xiyou_npc_xz_4',type:'SpriteAtlas'},

        {name:'gonji5',path:'plist/xiyou_npc_gj_5',type:'SpriteAtlas'},
        {name:'xinzou5',path:'plist/xiyou_npc_xz_5',type:'SpriteAtlas'},
    ],

    //攻击行走动画素材遍历数组
    attackAndWalkAni:[
        ['gonji1','xinzou1'],
        ['gonji2','xinzou2'],
        ['gonji3','xinzou3'],
        ['gonji4','xinzou4'],
        ['gonji5','xinzou5'],
    ],

    //技能素材遍历素组
    skillArrAni:['jineng','jineng1'],

    faceArr:[
        'touxiang2'
    ],

    //技能动画配置
    skillAni:{
        //baojin:{nmb:8},
        //cisa:{nmb:12},
        //du:{nmb:7},
        //feng:{nmb:14},
        //xixue:{nmb:14},
        //sui:{nmb:19},
        //huifu:{nmb:12},
        bao:{nmb:9},
        cisha:{nmb:6},
        an:{nmb:6},
        baoji:{nmb:4},
        bin:{nmb:12},
        buff:{nmb:5},
        debuff:{nmb:15},
        du:{nmb:14},
        feng:{nmb:17},
        hong:{nmb:14},
        huo:{nmb:10},
        lang:{nmb:14},
        lei:{nmb:13},
        putong:{nmb:4},
        sendun:{nmb:16},
        biansen:{nmb:12},
        zibao:{nmb:6},
        huolong:{nmb:10},
        xuanfenzan:{nmb:8},//以下为新
        //按五行分
        bh:{nmb:11},//变身召唤
        attack_bao:{nmb:4},//暴击
        attack_pu:{nmb:5},//普攻
        buff_boss:{nmb:13},//boss光环
        buff_dong:{nmb:6},//状态冰冻
        buff_du:{nmb:9},//状态中毒
        buff_dun:{nmb:9},//状态圣盾
        buff_huo:{nmb:12},//状态灼烧
        buff_yun:{nmb:8},//状态晕
        buff_mfhd:{nmb:12},//魔法护盾
        buff_up:{nmb:11},//升级
        cs:{nmb:6},//传送
        huo_dan:{nmb:9},//火单体
        jin_dan:{nmb:9},//金单体
        lan_dan:{nmb:8},//回蓝单体
        mu_dan:{nmb:12},//木单体
        shui_dan:{nmb:11},//水单体
        tu_dan:{nmb:7},//土单体
        wu_dan:{nmb:9},//刀单
        xue_dan:{nmb:10},//回血单体
        zao:{nmb:7},//招募
        ce_dan:{nmb:6},//策单
        jiang_dan:{nmb:7},//剑单
        jian_dan:{nmb:8},//箭单
        qiang_dan:{nmb:7},//枪单
        zou_dan:{nmb:9},//咒单
        wu_dan:{nmb:9},//物单
        zibao_dan:{nmb:9},//自爆
        


        // //jineng_1合图
        // huo_qun:{nmb:9},//火群
        // jin_qun:{nmb:13},//金群
        // lan_qun:{nmb:8},//回蓝群
        // mu_qun:{nmb:10},//木群
        // //jineng_2合图
        // shui_qun:{nmb:13},//水群
        // tu_qun:{nmb:7},//土群
        // wu_qun:{nmb:11},//物群
        // xue_qun:{nmb:13},//回血群


       
       
       
        // 按武器分类
        // buff_dun:{nmb:9},
        // ce_dan:{nmb:6},
        // dao_dan:{nmb:9},
        // gonji_bao:{nmb:4},
        // gonji_pu:{nmb:5},
        // jiang_dan:{nmb:7},
        // jian_dan:{nmb:8},
        // qiang_dan:{nmb:7},
        // zhao_dan:{nmb:7},
        // zou_dan:{nmb:9},
        // buff_dong:{nmb:6},
        // buff_cuang:{nmb:5},
        // buff_boss:{nmb:13},
        // buff_up:{nmb:11},
        // buff_yun:{nmb:8},
        // buff_du:{nmb:9},
        // buff_huo:{nmb:12},
        // ce_qun:{nmb:13},
        // dao_qun:{nmb:7},
        // jiang_qun:{nmb:10},
        // jian_qun:{nmb:15},
        // qiang_qun:{nmb:9},
        // zou_qun:{nmb:7},
        
    },
    resetAll:function(sence){
        _GRM.loadPrefabIndex = 0;
        _GRM.sence = sence;
        _GRM.loadAllPrefab();
    },
      
    getNode:function(prefabName){
        
        var result =_GRM.getNodeObj(prefabName); 
        if(result!=null)
        return result.node;
        
    },
    
    getNodeObj:function(prefabName){
        
        
        var resultNode = null,isnew = false;
        
        if(!window._GRM.node[prefabName]){
            window._GRM.node[prefabName] = new cc.NodePool();
        }
        
        if (window._GRM.node[prefabName].size() > 0) { 
            //console.log("从对象池中获取:"+prefabName);
            resultNode = window._GRM.node[prefabName].get();
        } else { 
            //console.log("新增:"+prefabName);
            resultNode=cc.instantiate(_GRM.prefab[prefabName]);
            resultNode.prefabType = prefabName;
            isnew = true;
            
            if(!window._GRM.nodecreate[prefabName])
                window._GRM.nodecreate[prefabName] = [];
            window._GRM.nodecreate[prefabName].push(resultNode);

        }
        
        resultNode.stopAllActions();
        
        return {node:resultNode,isnew:isnew};
        
    },

    putNode:function(node){
	 
        var prefabType = node.prefabType;
        
        if(!prefabType){
             //console.log("回收失败 prefabType:",prefabType);
             return 0;
        }
      
        if(!window._GRM.node[prefabType]){
            window._GRM.node[prefabType] = new cc.NodePool();
        }
         
        window._GRM.node[prefabType].put(node);
        //console.log("回收成功 prefabType:",prefabType);
        return 1;
        
    },
    
    
    getBackNode:function(parentNode){
    
        for(var i=0;i<parentNode.getChildren().length;){
            
            if(!_GRM.putNode(parentNode.getChildren()[i])){
                break;
            }
        }
    
    },
    
    getBackNodeSelf:function(node){
        _GRM.putNode(node);
    },

    //加载所有预制和资源
    loadAllPrefab:function(){
	   
        var res = window._GRM.prefabIndex[this.loadPrefabIndex];
        
        
        _GRM.sence.showMessage('加载'+res.name);
        

        if(!res.type){
            if(!window._GRM.prefab[res.name]||window._GRM.prefab[res.name].data==null){
            
                cc.loader.loadRes(res.path, function(errorMessage,loadedResource){
                    
                    if(errorMessage){
                        console.log('加载失败',res.name,errorMessage);
                    }
                     
                     window._GRM.prefab[res.name]=loadedResource;
                     
                     _GRM.afterLoadOnePrefab();
                     
                });
                
            }else{
                
                _GRM.afterLoadOnePrefab();
                
            }
        }else if(res.type=='SpriteAtlas'){
            if(!window._GRM.prefab[res.name]||window._GRM.prefab[res.name].data==null){
            
                cc.loader.loadRes(res.path,cc.SpriteAtlas,function(errorMessage,loadedResource){

                    if(errorMessage){
                        console.log('加载失败',res.name,errorMessage);
                    }
                     
                     window._GRM.prefab[res.name]=loadedResource;
                     
                     _GRM.afterLoadOnePrefab();
                     
                });
                
            }else{
                
                _GRM.afterLoadOnePrefab();
                
            }
        }
        
    },
    
    afterLoadOnePrefab:function(){
        
        _GRM.loadPrefabIndex++;
                 
         if(_GRM.loadPrefabIndex<window._GRM.prefabIndex.length){
             
            _GRM.loadAllPrefab();
             
         }else{
            //console.log('资源加载完成',_GRM.prefab);
            
            _GRM.sence.showMessage('资源加载完成');
            _GRM.sence.afterResLoad();
        
         }
        
    },
    
    showAll:function(){
        
        console.log("#####################对象使用情况:");
        
        for(var key in window._GRM.node){
            
            console.log(key+" enable: "+window._GRM.node[key].size()+" create:"+window._GRM.nodecreate[key].length);
            
        }
        
        console.log("#####################");
    },

    getEquipFrame:function(equipName){
        var equipfram = _GRM.prefab['equip'].getSpriteFrame(equipName);
        if(equipfram)
            return equipfram;
        else
            return _GRM.getFaceFrame(equipName);
    },

    getFaceFrame:function(faceName){
        for(var i=0;i<_GRM.faceArr.length;i++){
            var key = _GRM.faceArr[i];
            var tempface = _GRM.prefab[key].getSpriteFrame(faceName);
            if(tempface){
                return tempface;
            }
        }

        //console.log(faceName+'头像不存在');

        return _GRM.prefab['touxiang2'].getSpriteFrame(_CS.defaultFace)
        
    },

    getBuffFrame:function(frameName){
        return _GRM.prefab['buff'].getSpriteFrame(frameName)
    },

    getWalkFrame:function(aniName){

        //console.log('创建行走:',aniName);

        for(var i=0;i<_GRM.attackAndWalkAni.length;i++){

            var arr = _GRM.attackAndWalkAni[i];
            var xinzoukey = arr[1];
            if(_GRM.prefab[xinzoukey].getSpriteFrame(aniName+"_05")){
                return [
                    _GRM.prefab[xinzoukey].getSpriteFrame(aniName+"_05"),
                    _GRM.prefab[xinzoukey].getSpriteFrame(aniName+"_06"),
                ];
            }
        }

        return [];
    },

    getAttackFrame:function(aniName){

        for(var i=0;i<_GRM.attackAndWalkAni.length;i++){

            var arr = _GRM.attackAndWalkAni[i];
            var xinzoukey = arr[1];
            var attackkey = arr[0];
            if(_GRM.prefab[xinzoukey].getSpriteFrame(aniName+"_05")){
                return {
                        attack:[
                        _GRM.prefab[attackkey].getSpriteFrame(aniName+"_09"),
                        _GRM.prefab[attackkey].getSpriteFrame(aniName+"_10"),
                        _GRM.prefab[attackkey].getSpriteFrame(aniName+"_11"),
                        _GRM.prefab[attackkey].getSpriteFrame(aniName+"_12")
                        ],
                        walk:[
                        _GRM.prefab[xinzoukey].getSpriteFrame(aniName+"_05"),
                        _GRM.prefab[xinzoukey].getSpriteFrame(aniName+"_06")
                        ],
                        weak:[
                        _GRM.prefab[xinzoukey].getSpriteFrame(aniName+"_10"),
                        _GRM.prefab[xinzoukey].getSpriteFrame(aniName+"_11")
                        ]
                        //weak:_GRM.getSkillFrame('zibao_dan')
                };
            }
        }

        return  {
            attack:[],
            walk:[],
            weak:[]
        };
    },

    getSkillFrame:function(skillName){
        var arr=null;
        if(_GRM.skillAni[skillName]){
            arr=[];
            var config = _GRM.skillAni[skillName];
            var nmb = config.nmb;

            for(var k=0;k<_GRM.skillArrAni.length;k++){

                var key = _GRM.skillArrAni[k];
                
                if(_GRM.prefab[key].getSpriteFrame(skillName+"_01")){

                    for(var i=1;i<=nmb;i++){
                        var nmbstr=i;
                        if(i<10){
                            nmbstr="0"+i;
                        }
                        arr.push(_GRM.prefab[key].getSpriteFrame(skillName+"_"+nmbstr));
                    }

                    return arr;
                }

            }
        }

        return arr;
    },

    //cc.WrapMode.Normal  cc.WrapMode.Loop
    createAniClip:function(aniArr,aniname,loopType){
        var clipu = cc.AnimationClip.createWithSpriteFrames(aniArr, 10);
		clipu.name = aniname;
		clipu.wrapMode = loopType;
        return clipu;
    },

    createAniClipTime:function(aniArr,aniname,loopType,time){
        var clipu = cc.AnimationClip.createWithSpriteFrames(aniArr, time);
		clipu.name = aniname;
		clipu.wrapMode = loopType;
        return clipu;
    },

    createNpcSign:function(parentNode,position){
        var signNode = _GRM.getNode('npcSign');
        signNode.setPosition(position);
        parentNode.addChild(signNode);
    },

    createPlayerNode:function(aniName,taskname){
        var aniArr = _GRM.getWalkFrame(aniName);

        var bootArr = _GRM.getWalkFrame(_CS.boatAni);

        var playerNode = _GRM.getNode('player');
        playerNode.getComponent(cc.Sprite).spriteFrame = aniArr[0];
        var clipu = _GRM.createAniClip(aniArr,'walk',cc.WrapMode.Loop);
		playerNode.getComponent(cc.Animation).addClip(clipu);

        var boatclipu = _GRM.createAniClip(bootArr,'boatwalk',cc.WrapMode.Loop);
        playerNode.getComponent(cc.Animation).addClip(boatclipu);

        playerNode.getComponent(cc.Animation).play('walk');

        playerNode.getChildByName('shendun').active = false;

        playerNode.setScale(-_CS.playerScale,_CS.playerScale);

        if(taskname){
            playerNode.getChildByName('boss战').active = true;
            playerNode.getChildByName('boss战')
            .getChildByName('taskname').getComponent(cc.Label).string=taskname;
        }else{
            playerNode.getChildByName('boss战').active = false;
        }

        return playerNode;
    },

    createHitNode:function(skillName,msg,msgcolor,ismsgmove,msgdir){
        var hitNode = _GRM.getNode('hit');
        var aniNode = hitNode.getChildByName('ani');
        var msgParent = hitNode.getChildByName('xue');
        var msgNode = hitNode.getChildByName('xue').getChildByName('putong');
        if(skillName){
            aniNode.active = true;
            var aniarr = _GRM.getSkillFrame(skillName);
            if(aniarr){
                aniNode.getComponent(cc.Sprite).spriteFrame = aniarr[0];
                var clipu = _GRM.createAniClip(aniarr,skillName,cc.WrapMode.Normal);
                aniNode.getComponent(cc.Animation).addClip(clipu);
                aniNode.getComponent(cc.Animation).play(skillName);
            }else{
                aniNode.getComponent(cc.Sprite).spriteFrame = null;
            }
        }else{
            aniNode.active = false;
        }

        if(msg!=null){
            //msgNode.getComponent(cc.Label).string = msg;
            //console.log('数值加单位',msg,_CU.getUnitNmb(msg));
            msgNode.getComponent(cc.Label).string = _CU.getUnitNmb(msg);
            if(msgcolor){
                msgNode.color = new cc.color(msgcolor);
            }else{
                msgNode.color = new cc.color('#FFFFFF');
            }
            //msgNode.setScale(msgdir,1);
            msgParent.setPosition(0,0);
            if(ismsgmove)
            msgParent.runAction(cc.moveBy(0.1,0,20));
        }else{
            msgNode.getComponent(cc.Label).string ="";
        }

        return hitNode;
    },

    addHitOnPlayerNode:function(skillName,msg,playerNode,isplayer,param){

        var delayTime = _GRM.getAniPlayTime(skillName);
        var msgcolor =null
        var ismsgmove=null
        var msgdir =isplayer?-1:1;

        

        if(param){
            msgcolor=param.msgcolor;
            ismsgmove = param.ismsgmove;
            //delayTime = param.delayTime?param.delayTime:1;
            if(param.delayTime)
                delayTime = param.delayTime;
        }

        var hitNode = _GRM.createHitNode(skillName,msg,msgcolor,ismsgmove,msgdir);
        //hitNode.setScale(playerNode.getChildByName('role').scaleX,1);
        //playerNode.getChildByName('role').addChild(hitNode);

        //playerNode.getParent().getParent().getChildByName('messageLabel').addChild(hitNode);

        //console.log('技能动画:',skillName,delayTime);

        _CHESSFIGHT.messageLabel.addChild(hitNode);

        hitNode.setPosition(playerNode.getPosition());

        hitNode.runAction(cc.sequence(
            cc.delayTime(delayTime),
            cc.callFunc(function(){
                _GRM.getBackNodeSelf(this);
            },hitNode)
        ));

    },

    getAniPlayTime:function(skillName){

        if(skillName&&_GRM.skillAni[skillName]){
            //console.log('有动画配置',_GRM.skillAni[skillName].nmb,_GRM.skillAni[skillName].nmb/10);
            return _GRM.skillAni[skillName].nmb/10;
        }

        return 1;

    },

    testNpcResource:function(){

        for(var key in _NPC){

            //console.log('头像',_GRM.getFaceFrame(_NPC[key].face));
            _GRM.getFaceFrame(_NPC[key].face)
            var frameObj = _GRM.getAttackFrame(_NPC[key].pf);
            for(var type in frameObj){
                if(frameObj[type].length<=0){
                    console.log(key+' '+type+" 不存在");
                }else{
                    for(var i=0;i<frameObj[type].length;i++){
                        if(!frameObj[type][i]){
                            //console.log('形象',_GRM.getAttackFrame(_NPC[key].pf));
                            console.log(key+' '+type+" 不存在");
                            break;
                        }
                    }
                }
            }
            
        }

    }
}